package com.dragon.codefx.service;

import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * ZIP文件生成服务
 * 用于生成各种类型的ZIP压缩包
 *
 * @author lsc
 * @since 2025/9/26
 */
@Service
public class ZipFileGeneratorService {

    /**
     * 生成示例代码ZIP包
     */
    public File generateSampleCodeZip() throws IOException {
        String zipFileName = "sample-code-" + System.currentTimeMillis() + ".zip";
        Path tempDir = Files.createTempDirectory("codefx-temp");
        File zipFile = new File(tempDir.toFile(), zipFileName);

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            // 添加示例Java文件
            addJavaFileToZip(zos, "HelloWorld.java", generateHelloWorldCode());
            addJavaFileToZip(zos, "Utils.java", generateUtilsCode());
            addJavaFileToZip(zos, "README.md", generateReadmeContent());
            
            // 添加配置文件
            addFileToZip(zos, "config/application.properties", generatePropertiesContent());
        }

        return zipFile;
    }

    /**
     * 生成项目模板ZIP包
     */
    public File generateProjectTemplateZip(String projectName) throws IOException {
        String zipFileName = projectName + "-template-" + System.currentTimeMillis() + ".zip";
        Path tempDir = Files.createTempDirectory("codefx-temp");
        File zipFile = new File(tempDir.toFile(), zipFileName);

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            String packagePath = "src/main/java/com/example/" + projectName.toLowerCase() + "/";
            
            // 添加主类
            addFileToZip(zos, packagePath + "Application.java", generateApplicationCode(projectName));
            
            // 添加控制器
            addFileToZip(zos, packagePath + "controller/MainController.java", 
                generateControllerCode(projectName));
            
            // 添加服务类
            addFileToZip(zos, packagePath + "service/ExampleService.java", 
                generateServiceCode(projectName));
            
            // 添加配置文件
            addFileToZip(zos, "src/main/resources/application.yml", generateYmlConfig());
            addFileToZip(zos, "pom.xml", generatePomXml(projectName));
            addFileToZip(zos, "README.md", generateProjectReadme(projectName));
        }

        return zipFile;
    }

    /**
     * 生成日志文件ZIP包
     */
    public File generateLogFilesZip() throws IOException {
        String zipFileName = "logs-" + System.currentTimeMillis() + ".zip";
        Path tempDir = Files.createTempDirectory("codefx-temp");
        File zipFile = new File(tempDir.toFile(), zipFileName);

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            // 生成模拟日志文件
            addFileToZip(zos, "logs/application.log", generateApplicationLog());
            addFileToZip(zos, "logs/error.log", generateErrorLog());
            addFileToZip(zos, "logs/debug.log", generateDebugLog());
        }

        return zipFile;
    }

    /**
     * 将文件添加到ZIP包中
     */
    private void addFileToZip(ZipOutputStream zos, String fileName, String content) throws IOException {
        ZipEntry entry = new ZipEntry(fileName);
        zos.putNextEntry(entry);
        zos.write(content.getBytes("UTF-8"));
        zos.closeEntry();
    }

    /**
     * 将Java文件添加到ZIP包中
     */
    private void addJavaFileToZip(ZipOutputStream zos, String fileName, String content) throws IOException {
        addFileToZip(zos, "src/" + fileName, content);
    }

    // 以下是各种代码生成方法

    private String generateHelloWorldCode() {
        return "package com.example;\n\n" +
               "public class HelloWorld {\n" +
               "    public static void main(String[] args) {\n" +
               "        System.out.println(\"Hello, World!\");\n" +
               "        System.out.println(\"这是由 CodeFX 生成的示例代码\");\n" +
               "    }\n" +
               "}\n";
    }

    private String generateUtilsCode() {
        return "package com.example;\n\n" +
               "import java.time.LocalDateTime;\n" +
               "import java.time.format.DateTimeFormatter;\n\n" +
               "public class Utils {\n" +
               "    \n" +
               "    public static String getCurrentTime() {\n" +
               "        return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);\n" +
               "    }\n" +
               "    \n" +
               "    public static boolean isEmpty(String str) {\n" +
               "        return str == null || str.trim().isEmpty();\n" +
               "    }\n" +
               "}\n";
    }

    private String generateReadmeContent() {
        return "# 示例代码包\n\n" +
               "这是由 CodeFX 应用程序生成的示例代码包。\n\n" +
               "## 包含文件\n" +
               "- HelloWorld.java - 简单的 Hello World 程序\n" +
               "- Utils.java - 实用工具类\n" +
               "- config/application.properties - 配置文件\n\n" +
               "## 使用方法\n" +
               "1. 解压此ZIP文件\n" +
               "2. 导入到您的IDE中\n" +
               "3. 编译并运行\n\n" +
               "生成时间: " + java.time.LocalDateTime.now() + "\n";
    }

    private String generatePropertiesContent() {
        return "# 应用程序配置\n" +
               "app.name=CodeFX Generated Project\n" +
               "app.version=1.0.0\n" +
               "app.description=This is a generated project from CodeFX\n\n" +
               "# 日志配置\n" +
               "logging.level.root=INFO\n" +
               "logging.level.com.example=DEBUG\n";
    }

    private String generateApplicationCode(String projectName) {
        String className = capitalize(projectName) + "Application";
        return "package com.example." + projectName.toLowerCase() + ";\n\n" +
               "import org.springframework.boot.SpringApplication;\n" +
               "import org.springframework.boot.autoconfigure.SpringBootApplication;\n\n" +
               "@SpringBootApplication\n" +
               "public class " + className + " {\n" +
               "    \n" +
               "    public static void main(String[] args) {\n" +
               "        SpringApplication.run(" + className + ".class, args);\n" +
               "    }\n" +
               "}\n";
    }

    private String generateControllerCode(String projectName) {
        return "package com.example." + projectName.toLowerCase() + ".controller;\n\n" +
               "import org.springframework.web.bind.annotation.GetMapping;\n" +
               "import org.springframework.web.bind.annotation.RestController;\n\n" +
               "@RestController\n" +
               "public class MainController {\n" +
               "    \n" +
               "    @GetMapping(\"/\")\n" +
               "    public String hello() {\n" +
               "        return \"Hello from " + projectName + "!\";\n" +
               "    }\n" +
               "}\n";
    }

    private String generateServiceCode(String projectName) {
        return "package com.example." + projectName.toLowerCase() + ".service;\n\n" +
               "import org.springframework.stereotype.Service;\n\n" +
               "@Service\n" +
               "public class ExampleService {\n" +
               "    \n" +
               "    public String getWelcomeMessage() {\n" +
               "        return \"Welcome to " + projectName + " application!\";\n" +
               "    }\n" +
               "}\n";
    }

    private String generateYmlConfig() {
        return "spring:\n" +
               "  application:\n" +
               "    name: generated-project\n" +
               "  \nserver:\n" +
               "  port: 8080\n" +
               "\nlogging:\n" +
               "  level:\n" +
               "    com.example: DEBUG\n";
    }

    private String generatePomXml(String projectName) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
               "<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
               "         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
               "         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n" +
               "         http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" +
               "    <modelVersion>4.0.0</modelVersion>\n\n" +
               "    <groupId>com.example</groupId>\n" +
               "    <artifactId>" + projectName.toLowerCase() + "</artifactId>\n" +
               "    <version>1.0.0</version>\n" +
               "    <packaging>jar</packaging>\n\n" +
               "    <name>" + projectName + "</name>\n" +
               "    <description>Generated project by CodeFX</description>\n\n" +
               "    <parent>\n" +
               "        <groupId>org.springframework.boot</groupId>\n" +
               "        <artifactId>spring-boot-starter-parent</artifactId>\n" +
               "        <version>2.7.18</version>\n" +
               "        <relativePath/>\n" +
               "    </parent>\n\n" +
               "    <dependencies>\n" +
               "        <dependency>\n" +
               "            <groupId>org.springframework.boot</groupId>\n" +
               "            <artifactId>spring-boot-starter-web</artifactId>\n" +
               "        </dependency>\n" +
               "    </dependencies>\n\n" +
               "</project>\n";
    }

    private String generateProjectReadme(String projectName) {
        return "# " + projectName + "\n\n" +
               "这是由 CodeFX 生成的 Spring Boot 项目模板。\n\n" +
               "## 项目结构\n" +
               "```\n" +
               "src/\n" +
               "├── main/\n" +
               "│   ├── java/\n" +
               "│   │   └── com/example/" + projectName.toLowerCase() + "/\n" +
               "│   │       ├── Application.java\n" +
               "│   │       ├── controller/\n" +
               "│   │       └── service/\n" +
               "│   └── resources/\n" +
               "│       └── application.yml\n" +
               "└── pom.xml\n" +
               "```\n\n" +
               "## 快速开始\n" +
               "1. 解压项目文件\n" +
               "2. 导入到 IDE\n" +
               "3. 运行 `mvn spring-boot:run`\n" +
               "4. 访问 http://localhost:8080\n\n" +
               "生成时间: " + java.time.LocalDateTime.now() + "\n";
    }

    private String generateApplicationLog() {
        return "2025-09-26 10:00:00 INFO  [main] Application started successfully\n" +
               "2025-09-26 10:00:01 INFO  [main] Server started on port 8080\n" +
               "2025-09-26 10:05:23 INFO  [http-nio-8080-exec-1] Received request: GET /\n" +
               "2025-09-26 10:05:24 INFO  [http-nio-8080-exec-1] Response sent: 200 OK\n" +
               "2025-09-26 10:10:15 INFO  [scheduling-1] Scheduled task executed\n";
    }

    private String generateErrorLog() {
        return "2025-09-26 10:15:30 ERROR [http-nio-8080-exec-2] Database connection failed\n" +
               "2025-09-26 10:15:31 ERROR [http-nio-8080-exec-2] java.sql.SQLException: Connection timeout\n" +
               "2025-09-26 10:20:45 ERROR [main] Failed to initialize component\n";
    }

    private String generateDebugLog() {
        return "2025-09-26 10:00:00 DEBUG [main] Loading configuration from application.yml\n" +
               "2025-09-26 10:00:01 DEBUG [main] Initializing Spring context\n" +
               "2025-09-26 10:00:02 DEBUG [main] Registering beans...\n" +
               "2025-09-26 10:05:23 DEBUG [http-nio-8080-exec-1] Processing request parameters\n";
    }

    private String capitalize(String str) {
        if (str == null || str.isEmpty()) return str;
        return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
    }
}